<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class UserAmount extends AdminController{
	public $_validation = null;
	function __construct(){
		parent::__construct();
		$this->load->model('MUser');
		$this->_validation = Array();
	}

	/**
     *  玩家列表
	 */
	function index(){

		//$this->output->enable_profiler(TRUE);
		$this->load->library('FormFilter');
		$this->load->helper('formfilter');
		
		$this->formfilter->addFilter('id', 'where');
		$this->formfilter->addFilter('account','where');
		$this->formfilter->addFilter('status','where');
		
		$limit = $this->pagination($this->MUser->getCount());
		$list = $this->MUser->getList($limit);

		$this->assign('list', $list);
		$this->layout();
	}

	function edit($id){
		if(((int)$id) . '' !== $id){
			show_error(l('id_or_updated_not_null'));
		}
		if(!$user = $this->MUser->getById($id)){
			errorAndRedirect('此用户账号不存在！', site_url($this->_thisModule.$this->_thisController.'/edit/'.$id));
		}
		$this->load->model('MUserBank');
		$bank_info = $this->MUserBank->getUserBank($id);

		$this->assign('user', $user);
		$this->assign('bankInfo', $bank_info);
		$this->layout();
	}

	// 修改密码
	function changePass($id, $update_time){
		if(!$this->p->edit){
			//权限不足
			show_error(l('user_has_nopower'));
		}
		if(((int)$id) . '' !== $id){
			show_error(l('id_or_updated_not_null'));
		}
		// 跳转页面
		$redirectUrl = site_url($this->_thisModule.$this->_thisController.'/edit/'.$id);
		if(!$user = $this->MUser->getById((int)$id)){
			model_error('当前用户账号不存在！');
		}
		if ($update_time != $user->update_time) {
			model_error('操作冲突，请重试！');
		}
		$this->load->library('form_validation');
		$this->form_validation->set_rules('password', '密码', 'required');
		$this->form_validation->set_rules('password_confirm', '确认密码', 'required|matches[password]');
		if ($this->form_validation->run()) {
			// 密码修改
			$user->password = IOSS_User::hashPassword($this->input->post('password'));
			if(!$this->MUser->update($user)){
				model_error('数据库更新失败，请联系管理员！');
			}else{
				model_success('修改成功');
			}			
		}
		$this->assign('thisControllerName', '修改密码');
		$this->assign('user', $user);
		$this->layout_modal('change-pass');
	}

	// 改变玩家账户状态
	function toggleStatus($id, $update_time){
		if(!$this->p->edit){
			//权限不足
			show_error(l('user_has_nopower'));
		}
		if(((int)$id) . '' !== $id){
			show_error(l('id_or_updated_not_null'));
		}
		
		// 跳转页面
		$redirectUrl = site_url($this->_thisModule.$this->_thisController.'/edit/'.$id);
		if(!$user = $this->MUser->getById($id)){
			errorAndRedirect('此用户账号不存在！', $redirectUrl);
		}
		if ($update_time != $user->update_time) {
			errorAndRedirect('操作冲突，请重试！', $redirectUrl);
		}

		// 密码修改
		$user->status = !$user->status;
		if(!$this->MUser->update($user)){
			errorAndRedirect('数据库更新失败！', $redirectUrl);
		}
		successAndRedirect('状态修改成功！', $redirectUrl);
	}

	// 删除银行卡
	function deleteBank($user_id){
		if(!$this->p->edit){
			//权限不足
			show_error(l('user_has_nopower'));
		}
		if(!$user = $this->MUser->getById((int)$user_id)){
			show_error('当前用户账号不存在！');
		}		
		$this->load->model('MUserBank');
		if(!$bankInfo = $this->MUserBank->getUserBank($user_id)){
			show_error('当前用户没有有效用户通道！');
		}	

		$this->load->library('form_validation');
		$this->form_validation->set_rules('update_time', '更新时间', 'required');

		if ($this->form_validation->run()) {
			if ($this->input->post('update_time') != $user->update_time) {
				model_error('操作冲突，请重试！');
			}
			if(!$this->MUserBank->deleteBank($bankInfo->id)){
				model_error('数据库删除失败！');
			}else{
				model_success('删除成功');
			}
		}
		$this->assign('thisControllerName', '通道信息');
		$this->assign('bankInfo', $bankInfo);
		$this->assign('user', $user);
		$this->layout_modal('user-bank');
	}
	
	/**
	 * 客服请求某用户的游戏中余额
	 */
	function postRequestAmountInGame(){
	    $retObj = new stdClass();
	    if(!$this->p->edit){
	        //权限不足
	        $retObj->code = -1;
	        $retObj->message = l('user_has_nopower');
	        echo json_encode($retObj);
	        exit();
	    }
	    //获取用户信息
	    $userInfo = IOSS_User::getById($this->input->post('user_id'));
	    if(!$userInfo){
	        $retObj->code = -2;
	        $retObj->message = '用户不存在';
	        echo json_encode($retObj);
	        exit();
	    }
	    //查询游戏接口查余额===================================================
	    $accountAmount = IOSS_AGApi::agin_get_balance($userInfo->account,$userInfo->game_key);
	    if($accountAmount == 'error' || !$accountAmount){
	        $retObj->code = -3;
	        $retObj->message = '请求平台剩余数量接口失败';
	        echo json_encode($retObj);
	        exit();
	    }
	    //================================================================
	    //返回正确结果
	    $retObj->code = 1;
	    $retObj->amount = $accountAmount;
	    echo json_encode($retObj);
	}
	
	/**
	 * 客服操作余额变动
	 */
	function postWithdraw(){
	    $retObj = new stdClass();
	    if(!$this->p->edit){
	        //权限不足
	        $retObj->message = l('user_has_nopower');
	        echo json_encode($retObj);
	        exit();
	    }
	    //获取用户信息
	    $user_id = $this->input->post('user_id');
	    $user = IOSS_User::getById($user_id);
	    if(!$user){
	        $retObj->message = '用户不存在';
	        echo json_encode($retObj);
	        exit();
	    }
	    $withdraw_amount = $this->input->post('withdraw_amount');
	    //游戏接口提现===================================================
	    $billno = date('ymdHis') . rand(1000,9999);
	    // 预转账
	    if(!IOSS_AGApi::agin_prepare_transfer_credit($user->account, $user->game_key, $billno, 'OUT', $withdraw_amount, $prepare_error_message)){
	        $retObj->message = '预操作失败：'.$prepare_error_message["Message"];
	        echo json_encode($retObj);
	        exit();
	    }
	    // 转账确认
	    if (!IOSS_AGApi::agin_confirm_transfer_credit($user->account, $user->game_key, $billno, 'OUT', $withdraw_amount, $confirm_error_message)){
	        if ($confirm_error_message['Type'] === 'network_error') {
	            if (!IOSS_AGApi::agin_query_transfer_status($billno, $query_error_message)) {
	                $retObj->message = '订单状态确认未成功：'.$query_error_message["Message"];
	                echo json_encode($retObj);
	                exit();
	            }
	        }else{
	            $retObj->message = '确认平台转移操作失败：'.$confirm_error_message["Message"];
	            echo json_encode($retObj);
	            exit();
	        }
	    }
	    //===========================================================
	    //客服变更操作日志添加记录
	    $this->load->model('MHandleRecord');
	    $time = time();
	    $handleRecord = new stdClass();
	    $handleRecord->withdraw_no = NULL;
	    $handleRecord->user_id = $user_id;
	    $handleRecord->admin_id = $this->_user->id;
	    $handleRecord->admin_name = $this->_user->name;
	    $handleRecord->handle_type = 2;   //从游戏中提款
	    $handleRecord->withdraw_amount = NULL; //非提款表操作为NULL
	    $handleRecord->ingame_amount = $this->input->post('ingame_amount');
	    $handleRecord->handle_amount = $withdraw_amount;
	    $handleRecord->remark = '客服['.$this->_user->name.']操作：将账号为 '.$user->account.' 的用户平台内数量提出 '.$withdraw_amount;
	    $handleRecord->create_time = $time;
	    $handleRecord->update_time = $time;
	    $this->MHandleRecord->add($handleRecord);
	    
	    $retObj->message = '客服['.$this->_user->name.']操作：将账号为 '.$user->account.' 的用户平台内数量提出 '.$withdraw_amount;
	    echo json_encode($retObj);
	    exit();
	}
}